/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package construtora.limiar.servlet;

import construtora.limiar.constants.Papeis;
import construtora.limiar.dao.ClienteDAO;
import construtora.limiar.dao.FuncionarioDAO;
import construtora.limiar.dao.ImovelDAO;
import construtora.limiar.dao.ObraDAO;
import construtora.limiar.mensagens.Message;
import construtora.limiar.models.Funcionario;
import construtora.limiar.models.Imovel;
import construtora.limiar.models.Obra;
import construtora.limiar.models.Usuario;
import construtora.limiar.models.generic.AbstractCliente;
import construtora.limiar.util.AuthorizationController;
import construtora.limiar.util.Utilidades;
import java.io.IOException;
import java.sql.Date;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author michel
 */
@WebServlet(name = "ObraSlt", urlPatterns = {"/ObraSlt"})
public class ObraSlt extends AuthSlt {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        operacao = request.getParameter("operacao");
        chave = request.getParameter("chave");

        RequestDispatcher rd = null;
        /*
         Usuario usuario = (Usuario) getServletContext().getAttribute("usuario");
         AuthorizationController ac = AuthorizationController.getInstance(usuario.getApelido());
        
         if (!ac.hasRole(new String[]{Papeis.GRAVADOR,Papeis.ADMINISTRADOR})){
         Message.setLastInfo("Você não tem permissão para usar este recurso!");
         response.sendRedirect("admin.jsp");
         return;
         }
        
         String cadastro = request.getParameter("cadastro");
         String retornar = request.getParameter("retornar");
         if (retornar != null) {
         response.sendRedirect("cadastro.jsp?cadastro=" + cadastro);
         return;
         }
         if (request.getCharacterEncoding() == null)
         request.setCharacterEncoding("UTF-8");

        
         */
        if ("incluir".equals(operacao)) {
            AbstractCliente cliente = new AbstractCliente() {
                @Override
                public String getIdentificacao() {
                    throw new UnsupportedOperationException("Not supported yet.");
                }

                @Override
                public void setIdentificacao(String identificacao) {
                    throw new UnsupportedOperationException("Not supported yet.");
                }

                @Override
                public String getDocumento() {
                    throw new UnsupportedOperationException("Not supported yet.");
                }

                @Override
                public void setDocumento(String documento) {
                    throw new UnsupportedOperationException("Not supported yet.");
                }
            };
            Imovel imovel = new Imovel();
            imovel.setId(Integer.parseInt(chave));
            ImovelDAO dao = new ImovelDAO();
            ClienteDAO cliDao = new ClienteDAO();
            imovel = (Imovel) dao.fetchOne(imovel);
            List list = cliDao.fetchAll("id_cliente = '" + imovel.getCliente().getId() + "'", null, null, null);
            cliente = (AbstractCliente) list.get(0);
            FuncionarioDAO funDao = new FuncionarioDAO();
            List funcionarios = funDao.fetchAll("status = 'ativo'", null, null, null);
            request.setAttribute("imovel", imovel);
            request.setAttribute("cliente", cliente);
            request.setAttribute("funcionarios", funcionarios);
            rd = request.getRequestDispatcher("/gravarObra.jsp");
        } else if ("gravar".equals(operacao)) {
            Obra obra = new Obra();
            ObraDAO dao = new ObraDAO();
            obra.setImovel(new Imovel(Integer.parseInt(request.getParameter("id_imovel"))));
            obra.setEngenheiro(new Funcionario(Integer.parseInt(request.getParameter("id_engenheiro"))));
            obra.setArquiteto(new Funcionario(Integer.parseInt(request.getParameter("id_arquiteto"))));
            obra.setPaisagista(new Funcionario(Integer.parseInt(request.getParameter("id_paisagista"))));
            obra.setStatus(request.getParameter("status"));
            obra.setDescricao(request.getParameter("descricao"));
            Date dataInicio = Utilidades.trataData(request.getParameter("data_inicio"));
            Date dataPrevista = Utilidades.trataData(request.getParameter("data_prevista"));
            obra.setDataInicio(dataInicio);
            obra.setDataPrevista(dataPrevista);
            if (obra.getId() == null) {
                dao.insert(obra);
                obra.setId(dao.getLast(obra));
            } else {
                dao.update(obra);
            }
            rd = request.getRequestDispatcher("ClienteSlt?operacao=listar&chave=" + request.getParameter("cliente_id"));
        } else if ("editar".equals(operacao)) {
            //
        } else if ("gravaralteracao".equals(operacao)) {
            //
        } else if ("listar".equals(operacao)) {
            //
        } else if ("excluir".equals(operacao)) {
            //
        }
        if (rd != null) {
            rd.forward(request, response);
        }

    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
